package com.longway.core.ext.excel.util;

import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.List;
import java.util.Vector;

import com.longway.core.ext.excel.data.ColumnMeta;


public class TableKit
{
    private String tableName;
    private List<ColumnMeta> columns = new Vector<ColumnMeta>();
    private HashMap<String, Integer> columnIndex = new HashMap<String, Integer>();

    public TableKit(ResultSet table)
    {
        try
        {
            ResultSetMetaData tba = table.getMetaData();
            int count = tba.getColumnCount();

            tableName = tba.getTableName(1);

            for (int i = 1; i <= count; i++)
            {
                String columnName = tba.getColumnLabel(i);
                Integer type = tba.getColumnType(i);
                String typeName = tba.getColumnTypeName(i);
                Integer precision = tba.getScale(i);
                Integer length = tba.getPrecision(i);
                Integer nullable = tba.isNullable(i);

                columnIndex.put(columnName, columns.size());
                columns.add(new ColumnMeta(columnName, typeName, type, length, precision, nullable));

            }
        }
        catch (SQLException e)
        {
            e.printStackTrace();
        }
    }

    public ColumnMeta getColumn(String name)
    {
        int pos = columnIndex.get(name);
        return columns.get(pos);
    }

    public ColumnMeta getColumn(int pos)
    {
        return columns.get(pos);
    }

    public boolean hasColumn(String name)
    {
        if (columnIndex.containsKey(name))
        {
            return true;
        }

        return false;
    }

    public String getTableName()
    {
        return tableName;
    }

    public int size()
    {
        return columns.size();
    }
}
  
